package com.lxq.web;

import com.lxq.entity.User;
import com.lxq.service.impl.UserServiceImpl;
import com.lxq.util.TransactionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author 龙小虬
 * @date 2021/4/22 21:06
 */
@RestController
public class UserController {

    @Autowired
    UserServiceImpl userService;

    @Autowired
    TransactionUtil transactionUtil;

    @GetMapping("/add")
//    @Transactional
    public String add(String name, String age) {
        TransactionStatus begin = transactionUtil.begin();
        boolean isTrue = false;
        try {
            isTrue = userService.save(new User(name, age));
            int j = 1 / 0;
            transactionUtil.commit(begin);
        } catch (Exception e) {
            if (begin != null)
                transactionUtil.rollback(begin);
        }
        return isTrue ? "success" : "fail";
    }

    @GetMapping("/update")
    public String update(int id, String name, String age) {
        TransactionStatus begin = transactionUtil.begin();
        boolean isTrue = userService.updateById(new User(id, name, age));
        return isTrue ? "success" : "fail";
    }

    @GetMapping("/updateUser")
    public String updateUser(int id, String name, String age) {
        TransactionStatus begin = transactionUtil.begin();
        boolean isTrue = userService.updateById(new User(id, name, age));
        transactionUtil.commit(begin);
        return isTrue ? "success" : "fail";
    }

//    @GetMapping("/updateData")
//    public String updateData(int id, String name, String age) {
//        boolean isTrue = false;
//        double version = userService.getById(id).version;
//        int count = 0;
//        while (true) {
//            isTrue = userService.updateById(id, name, age, version);
//            if (!isTrue) {
//                version = userService.getById(id).version;
//                count++;
//            }
//            if (count >= 5) {
//                break;
//            }
//        }
//        return isTrue ? "success" : "fail";
//    }
}
